﻿using AutoMapper;
using Comm100.Application.Services;
using Comm100.Framework.Auditing;
using Comm100.Framework.Authorization;
using Comm100.Public.Audit;
using Bot.Application.Dto;
using Bot.Application.Services;
using Bot.Domain.Bo;
using Bot.Domain.Entities;
using Bot.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using Bot.Domain;

namespace Bot.Application.BackgroundJobs.Service
{
    public class BackgroundJobAppService : BaseAppService, IBackgroundJobAppService
    {
        private IBackgroundJobDomainService _domainService;

        public BackgroundJobAppService(IBackgroundJobDomainService domainService) : base()
        {
            this._domainService = domainService;
        }

        [Authorization(BotPermission.MANAGE_BOTS)]
        [Audit(BotEntity.BACKGROUNDJOB, AuditAction.DESTROY)]
        public void Delete(Guid id)
        {
            _domainService.Delete(id);
        }

        [Authorization(BotPermission.MANAGE_BOTS)]
        [Audit(BotEntity.BACKGROUNDJOB, AuditAction.CREATE)]
        public BackgroundJobDto Add(BackgroundJobCreateDto dto)
        {
            BackgroundJob backgroundJob = _domainService.Create(Mapper.Map<BackgroundJob>(dto));
            return Mapper.Map<BackgroundJobDto>(backgroundJob);
        }

        [Authorization(BotPermission.MANAGE_BOTS)]
        [Audit(BotEntity.BACKGROUNDJOB, AuditAction.UPDATE)]
        public BackgroundJobDto Update(BackgroundJobUpdateDto dto)
        {
            BackgroundJob backgroundJob = _domainService.Update(Mapper.Map<BackgroundJobUpdateBo>(dto));
            return Mapper.Map<BackgroundJobDto>(backgroundJob);
        }

        public OperationDto Get(Guid id)
        {
            if (!_domainService.ExistsJob(id))
            {
                ErrorInfo errorInfo = new ErrorInfo { Code = 1 };
                errorInfo = APIHelper.GetErrorMessageByCode(50004);
                throw new BusinessException(errorInfo);
            }
            Operation operation = _domainService.GetOperation(id);
            return Mapper.Map<OperationDto>(operation);
        }

        public IEnumerable<BackgroundJobDto> GetList()
        {
            IEnumerable<BackgroundJob> list = _domainService.List();
            return Mapper.Map<IEnumerable<BackgroundJobDto>>(list);
        }
    }
}
